package com.netintech.intelligenceInterface.iflytek.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date;

import static com.netintech.intelligenceInterface.common.StaticBean.LOCAL_DATE_FORMAT;

/**
 * @author lining
 * @date 2021/4/30 15:52
 */
public class AuthTest {
    private static String API_KEY = "testhls";
    private static String API_SECRET = "4B446FF1975C4E608B53DF716D3CDB68";

    public static void main(String[] args) {
        Date date = new Date();
        String dateString = LOCAL_DATE_FORMAT.get().format(date);
        System.out.println(dateString);

        String url = "http://172.16.11.211:10001/test";
        try {
            URL uri = new URL(url);
            String host = uri.getHost();
            StringBuilder builder = new StringBuilder().
                    append("host: ").append(host).append("\n").
                    append("date: ").append(dateString).append("\n").
                    append("POST").append(" ").append(uri.getPath()).append(" HTTP/1.1");
            Mac mac = Mac.getInstance("hmacsha256");
            System.out.println(builder.toString());
            SecretKeySpec spec = new SecretKeySpec(API_SECRET.getBytes(StandardCharsets.UTF_8), "hmacsha256");
            mac.init(spec);
            byte[] hexDigits = mac.doFinal(builder.toString().getBytes(StandardCharsets.UTF_8));
            String sha = Base64.getEncoder().encodeToString(hexDigits);
            System.out.println(sha);
            String headers = "host date request-line";
            String authorization = String.format("hmac api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", API_KEY, "hmac-sha256", headers, sha);
            System.out.println(authorization);
        } catch (MalformedURLException | NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
    }
}
